package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Test1;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service(version = "1.0.0")
public class Test1ApiImpl implements Test1Api{
@Autowired
private MongoTemplate mongoTemplate;
    @Override
    public Boolean save(Long userId, Boolean likeOpen, Boolean commentOpen, Boolean announcementOpen) {
        try {
            Test1 test11 = this.find(userId);
            if (test11==null) {
                Test1 test1 = new Test1();
                test1.setId(ObjectId.get());
                test1.setUserId(userId);
                test1.setLikeOpen(likeOpen);
                test1.setCommentOpen(commentOpen);
                test1.setAnnouncementOpen(announcementOpen);
                this.mongoTemplate.save(test1);
            }else {
                Update update = new Update();
                update.set("likeOpen", likeOpen);
                update.set("commentOpen", commentOpen);
                update.set("announcementOpen", announcementOpen);
                Query query = Query.query(Criteria.where("userId").is(userId));
                this.mongoTemplate.updateFirst(query, update, Test1.class);
            }
                return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Test1 find(Long userId) {
        Query query=Query.query(Criteria.where("userId").is(userId));
        return this.mongoTemplate.findOne(query,Test1.class);
    }
}
